﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BartonExtension;

using Model.App;

using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage;
using Senparc.Weixin.MP.CommonAPIs;

using Services.Common;

namespace Services.Weixin
{
    public class ISMWeixinServiceProvider : ISMServiceProvider
    {
        public const string WEIXIN_PUSH = "weixinpush";
        public override Task<ISMServiceResult> doProcess(ISMServiceModel model)
        {
            if(model.operationIdentifier == WEIXIN_PUSH)
            {
                return WeixinPush(model.GetState<ISMWeixinPushRequest>());
            }
            else
            {
                return base.defaultProcess();
            }
        }

        private Task<ISMServiceResult> WeixinPush(ISMWeixinPushRequest request)
        {
            return Task.Factory.StartNew<ISMServiceResult>(() =>
            {
                ISMServiceResult result = new ISMServiceResult();
                string token = GetAccessToken();
                var messageSendResult = GroupMessageApi.SendGroupMessageByOpenId(token, Senparc.Weixin.MP.GroupMessageType.text, "有来自{0} 的消息 :".FormatWith(request.from) + request.pushcontent, 10000, new string[]{request.openid});
                if(messageSendResult.errcode != 0)
                {
                    result.isOperationSuccess = false;
                    result.errorMsg = messageSendResult.errmsg;
                    result.errorCode = ISMServiceResultErrorCodes.ERR_CODE_ISM_UNKNOWN_ERR;
                }
                return result;
            });
        }


        private string GetAccessToken()
        {
            if (!AccessTokenContainer.CheckRegistered(ConfigurationExtensions.ValueOfConfig("weixin_app_id")))//检查是否已经注册
            {
                AccessTokenContainer.Register(ConfigurationExtensions.ValueOfConfig("weixin_app_id"), ConfigurationExtensions.ValueOfConfig("weixin_app_secret"));//如果没有注册则进行注册
            }
            var result = AccessTokenContainer.TryGetToken(ConfigurationExtensions.ValueOfConfig("weixin_app_id"), ConfigurationExtensions.ValueOfConfig("weixin_app_id")); //获取AccessToken结果
            return result;
        }
    }
}
